package com.guqj.mq.activitemq.queue;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 消息消费者
 * 
 * @author guqj
 * 
 */
public class JmsConsumer {

	// null
	private static final String USERNAME = ActiveMQConnection.DEFAULT_USER;
	// null
	private static final String PASSWORD = ActiveMQConnection.DEFAULT_PASSWORD;
	// failover://tcp://localhost:61616
	private static final String BOKER_URL = ActiveMQConnection.DEFAULT_BROKER_URL;

	/**
	 * 创建Session
	 * 
	 * @return
	 * @throws JMSException
	 */
	public Connection createConnection() throws JMSException {
		// 实例化连接工厂
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				USERNAME, PASSWORD, BOKER_URL);
		// 通过连接工厂获取连接
		Connection connection = connectionFactory.createConnection();
		// 启动连接
		connection.start();
		return connection;
	}

	/**
	 * 获取消息消费者
	 * 
	 * @param session
	 * @param queue
	 * @return
	 * @throws JMSException
	 */
	public MessageConsumer createConsumer(Session session, String queue)
			throws JMSException {
		// 创建队列
		Destination destination = session.createQueue(queue);
		// 创建消费者
		MessageConsumer messageConsumer = session.createConsumer(destination);
		return messageConsumer;
	}

	/**
	 * 接收消息
	 * 
	 * @param messageProducer
	 * @param message
	 * @throws JMSException
	 */
	public void receiveMessage(MessageConsumer messageConsumer)
			throws JMSException {
		while (true) {
			Message message = messageConsumer.receive(10000);
			if (null != message) {
				System.out.println("接收到的消息："
						+ ((TextMessage) message).getText());
			} else {
				break;
			}
		}
	}

	public static void main(String[] args) {
		String queue = "MyQueue@1";
		JmsConsumer p = new JmsConsumer();
		Session session = null;
		Connection connection = null;
		try {
			connection = p.createConnection();
			// 创建session
			session = connection.createSession(Boolean.FALSE,
					Session.AUTO_ACKNOWLEDGE);
			MessageConsumer messageConsumer = p.createConsumer(session, queue);
			p.receiveMessage(messageConsumer);
		} catch (JMSException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != connection) {
					connection.close();
				}
				if (null != session) {
					session.close();
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
	}
}
